package com.example.dao;

import com.example.entity.ClassInfo;
import com.example.model.PageBean;
import com.mysql.cj.util.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ClassDao {
    public ResultSet getClassList(Connection connection, PageBean pageBean, ClassInfo clafo) throws SQLException {
        StringBuffer sb = new StringBuffer("select * from t_class");
        if (clafo != null && !StringUtils.isNullOrEmpty(clafo.getClassName())) {
            sb.append(" and className like '%" + clafo.getClassName() + "%'");
        }

        if (pageBean != null) {
            sb.append(" limit " + pageBean.getStart() + "," + pageBean.getRows());
        }

        PreparedStatement pstmt = connection.prepareStatement(sb.toString().replaceFirst("and", "where"));
        return pstmt.executeQuery();
    }

    public int count(Connection con,ClassInfo clafo) throws SQLException {
        StringBuffer sb = new StringBuffer("select count(*) as total from t_class");
        //空指针异常处理
        if(clafo!=null){
            if (StringUtils.isNullOrEmpty(clafo.getClassName())) {
                sb.append(" and className like '%" + clafo.getClassName() + "%'");
            }
        }

        PreparedStatement pstmt = con.prepareStatement(sb.toString().replaceFirst("and", "where"));
        ResultSet rs = pstmt.executeQuery();
        if (rs.next()) {
            return rs.getInt("total");
        } else {
            return 0;
        }
    }

    public int insertClass(Connection con, ClassInfo classInfo) throws SQLException {
        String sql="INSERT INTO t_class value(null,?,?) ";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setString(1, classInfo.getClassDesc());
        pstmt.setString(2, classInfo.getClassName());
        return pstmt.executeUpdate();
    }

    public int updateClass(Connection con, ClassInfo classInfo) throws SQLException {
        String sql="UPDATE t_class set className=?,classDesc=? where id=?";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setString(1,classInfo.getClassName());
        pstmt.setString(2, classInfo.getClassDesc());
        pstmt.setInt(3, classInfo.getId());
        return pstmt.executeUpdate();
    }

    /**
     * 删除操作  delete from t_calss where id in (1,3,5)
     * @param con
     * @param delIds
     * @return
     * @throws SQLException
     */
    public int deleteClass(Connection con, String ids) throws SQLException {
        String sql="delete from t_class where id in ("+ids+")";
        PreparedStatement pstmt=con.prepareStatement(sql);
        return pstmt.executeUpdate();
    }


}
